<template>
  <!-- 登陆界面组件 -->
  <div class="login-body">
    <!-- 背景图片 -->
    <div class="bg"></div>
    <!-- 登录表单 -->
    <div class="login-panel">
      <el-form
        class="login-register"
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        @submit.prevent
      >
        <div class="login-title">R-Pan云盘</div>
        <el-form-item prop="email">
          <el-input
            size="large"
            clearable
            placeholder="请输入邮箱"
            v-model.trim="formData.email"
            maxlength="150"
          >
            <template #prefix>
              <span class="iconfont icon-account"></span>
            </template>
          </el-input>
        </el-form-item>
        <!-- 用户名 -->
        <el-form-item prop="username" v-if="oprType == 0">
          <el-input
            clearable
            size="large"
            placeholder="请输入用户名"
            v-model.trim="formData.username"
            maxlength="20"
          >
            <template #prefix>
              <span class="iconfont icon-account"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            clearable
            size="large"
            show-password
            placeholder="请输入密码"
            v-model.trim="formData.password"
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="rePassword" v-if="oprType == 0 || oprType == 2">
          <el-input
            type="password"
            clearable
            size="large"
            show-password
            placeholder="请再次输入密码"
            v-model.trim="formData.rePassword"
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>
        <div v-if="oprType == 0 || oprType == 2">
          <!-- 获取邮箱验证码 -->
          <el-form-item prop="emailCode">
            <div class="send-email-panel">
              <el-input
                size="large"
                clearable
                placeholder="请输入邮箱验证码"
                v-model.trim="formData.emailCode"
              >
                <template #prefix>
                  <span class="iconfont icon-checkcode"></span>
                </template>
              </el-input>
              <!-- 发送邮箱验证码按钮 -->
              <el-button
                type="primary"
                class="send-email-btn"
                size="large"
                @click="sendEmailCode"
                >获取验证码
              </el-button>
            </div>
            <el-popover placement="left" :width="500" trigger="click">
              <div>
                <p>1、在回收站中查找邮箱验证码</p>
                <p>2、在邮箱设置中将邮箱【】加入白名单</p>
              </div>
              <template #reference>
                <span class="a-link" :style="{ 'font-size': '14px' }"
                  >未收到邮箱验证码
                </span>
              </template>
            </el-popover>
          </el-form-item>
        </div>
        <ImageCodeFormItem
          :formData="formData"
          :imageCodeType="0"
          ref="imageCodeFormItemRef"
        />
        <div class="remember-me-panel">
          <el-checkbox v-model="formData.rememberMe">记住我</el-checkbox>
        </div>
        <el-form-item v-if="oprType == 1">
          <div class="no-account">
            <a
              href="javascript:void(0)"
              class="a-link"
              @click="changeOprType(2)"
              >忘记密码？</a
            >
            <a
              href="javascript:void(0)"
              class="a-link"
              @click="changeOprType(0)"
              >没有账号？</a
            >
          </div>
        </el-form-item>
        <el-form-item v-else>
          <div class="no-account">
            <a
              href="javascript:void(0)"
              class="a-link"
              @click="changeOprType(1)"
              >去登陆？</a
            >
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="op-btn"
            size="large"
            @click="submitForm"
          >
            <span v-if="oprType == 0">注册</span>
            <span v-if="oprType == 1">登录</span>
            <span v-if="oprType == 2">重置密码</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
  <SendEmailCodeDialog
    ref="sendEmailCodeDialogRef"
    :email="formData.email"
    :oprType="oprType.value"
  />
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

/* 发送邮箱验证码弹框组件 */
import SendEmailCodeDialog from "./SendEmailCodeDialog.vue";
const sendEmailCodeDialogRef = ref(null);
const sendEmailCode = async () => {
  // 需要先输入邮箱后才能发送邮箱验证码
  formDataRef.value.validateField("email", (valid) => {
    if (!valid) return;
    sendEmailCodeDialogRef.value.show();
  });
};

/* 获取图片验证码的表单项 */
import ImageCodeFormItem from "@/components/ImageCodeFormItem.vue";

const imageCodeFormItemRef = ref(null);
// 操作类型 0:注册 1:登录 2:找回密码
const oprType = ref(1);
const changeOprType = (type) => {
  oprType.value = type;
  // 重置表单数据
  formDataRef.value.resetFields();
  formData.value = {};
  // 重新获取图片验证码
  imageCodeFormItemRef.value.changeImageCode();
};

/* 校验两次密码是否输入一致 */
const checkRePassword = (rule, value, callback) => {
  if (value !== formData.value.password) {
    return callback(new Error(rule.message));
  } else {
    return callback();
  }
};

const formData = ref({});
const formDataRef = ref();
const rules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { validator: proxy.Verify.email, message: "邮箱格式错误", trigger: "blur" },
  ],
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      validator: proxy.Verify.username,
      message: "用户名由4到12位的中文、字母、数字和横杆组成",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      validator: proxy.Verify.password,
      message: "密码需要是8位及以上数字、字母、符号两种及以上的组合",
      trigger: "blur",
    },
  ],
  rePassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      validator: checkRePassword,
      message: "两次密码输入不一致",
      trigger: "blur",
    },
  ],
  imageCode: [{ required: true, message: "请输入图片验证码", trigger: "blur" }],
  emailCode: [{ required: true, message: "请输入邮箱验证码", trigger: "blur" }],
};

import { md5 } from "js-md5";

/* 提交表单 */
const submitForm = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = {};
    Object.assign(params, formData.value);
    let url = "";
    let msg = "";
    switch (oprType.value) {
      case 0:
        url = proxy.Api.register;
        msg = "注册成功";
        break;
      case 1:
        url = proxy.Api.login;
        // 密码需要md5加密
        params.password = md5(params.password);
        msg = "登录成功";
        break;
      case 2:
        url = proxy.Api.resetPassword;
        msg = "重置密码成功";
        break;
      default:
        return;
    }
    let result = await proxy.Request({
      method: "post",
      url,
      params,
    });
    if (!result) {
      // 失败要重新获取图片验证码
      imageCodeFormItemRef.value.changeImageCode();
      return;
    }
    if (oprType.value != 1) {
      // 回到登陆界面
      changeOprType(1);
    } else {
      // 去到首页
      router.push("/home");
    }
    proxy.Message.success(msg);
  });
};
</script>

<style lang="scss" scoped>
.login-body {
  height: calc(100vh);
  background-size: cover;
  background: url("../assets/login_bg.jpg");
  display: flex;
  .bg {
    flex: 1;
    background-position: center;
    background-size: 600px;
    background-repeat: no-repeat;
    background-image: url("../assets/login_img.png");
  }
  .login-panel {
    width: 400px;
    margin-right: 15%;
    margin-top: calc((100vh - 500px) / 2);
    .login-register {
      padding: 25px;
      background: #fff;
      border-radius: 5px;
      .login-title {
        text-align: center;
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
      }
      .send-email-panel {
        display: flex;
        width: 100%;
        justify-content: space-between;
        .send-email-btn {
          margin-left: 5px;
        }
      }
      .remember-me-panel {
        width: 100%;
      }
      .no-account {
        width: 100%;
        display: flex;
        justify-content: space-between;
      }
      .op-btn {
        width: 100%;
      }
    }
  }
  .login-btn-qq {
    margin-top: 20px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      cursor: pointer;
      margin-left: 10px;
      width: 20px;
    }
  }
}
</style>
